﻿
var ckConfig = {
    filebrowserImageUploadUrl: '/SystemSetting/CKEditorUploadImage',
    skin: 'office2003',
    toolbar: 'Full'
};

ckConfig.toolbar = [
   
         { name: 'insert', items: ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe'] },

     '/',
     { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'] },
     { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl'] },
     { name: 'links', items: ['Link', 'Unlink', 'Anchor'] },
      '/',
      { name: 'styles', items: ['Styles', 'Format', 'Font', 'FontSize'] },
      { name: 'colors', items: ['TextColor', 'BGColor'] }
      ];


//init
      $(function () {

          CKEDITOR.replace('TravelFeature', ckConfig);
          CKEDITOR.replace('ChargeInclude', ckConfig);
          CKEDITOR.replace('Tips', ckConfig);
          CKEDITOR.replace('Remark', ckConfig);

          $("#dialog-message").dialog({
              autoOpen: false,
              modal: true,
              width: 900,
              height: 600,
              position: 'top',
              buttons: {}
          });

          $("#dialog-chargeproject").dialog({
              autoOpen: false,
              modal: true,
              width: 900,
              height: 500,
              buttons: {}
          });

          //验证设置
          $("#form1").validate({
              rules: {
                  Name: "required",
                  PlanUserCount: "required",
                  BeginTravelDate: { required: true, dateISO: true },
                  EndTravelDate: { required: true, dateISO: true }
              },
              messages: {
                  Name: "*必填项",
                  PlanUserCount: "*必填项",
                  BeginTravelDate: { required: "*", dateISO: "*请输入正确格式" },
                  EndTravelDate: { required: "*", dateISO: "*请输入正确格式" }
              },
              submitHandler: function (form) {
                  //提取日期规则数据
                  if (ruleInex != -1) {
                      var rule = ruleInex + "|";
                      ruleInex = parseInt(ruleInex);

                      switch (ruleInex) {
                          case 0: //week
                              $("input[name='ruleWeek']:checked").each(function (i) {
                                  rule = rule + $(this).val() + ",";
                              });

                              rule = rule.substr(0, rule.length - 1);
                              break;
                          case 1: //custom date
                              //提取发团日期
                              var dates = $("#ulCalendar").attr("value").split(",");
                              rule = "";
                              for (var i = 0; i < dates.length; i++) {
                                  if (dates[i] != "")
                                      rule += dates[i] + ",";
                              }
                              if (rule == "") {
                                  alert("请选择发团日期!");
                                  return;
                              }
                              rule = "1|" + rule.substr(0, rule.length - 1);

                              break;
                          case 2: //interval  day
                              rule = rule + $("#ruleInterval").val();
                              break;
                      }

                      if ($("#TourID").val() == "" || rule == "" || rule.length <= 2) {
                          alert("请设置出团日期规则");
                          return;
                      }

                      $("#TravelDateRule").val(rule);
                  }

                  form.submit();
              }

          });
          //end validate


          datePicker("#BeginTravelDate");
          datePicker("#EndTravelDate");
          orderCal();
          //selRule(0); //选中日期规则
          $("#tabs").tabs();

          //选择日期
          $("#TravelDayCount").change(function () {

              var iDay = $(this).val(); //行程天数
              var iCal = $(".tbCalendar").length - 1;

              if (iDay > iCal) {
                  for (var i = 0; i < iDay - iCal; i++) {
                      //添加行
                      var tr = $("#tbCalendarTemplate").clone();
                      tr.appendTo("#calContainer");
                      tr.show();

                      var id = "tbCalendar" + Math.random();
                      tr.attr("id", id);

                      var TC_TravelContent = $(".TC_TravelContent", tr);
                      var id = "TC_TravelContent" + (Math.random() + "").substr(2);
                      TC_TravelContent.attr("id", id);
                  }
              }

              if (iDay < iCal) {
                  for (var i = 0; i < iCal - iDay; i++) {
                      //删除行
                      $(".tbCalendar:visible").last().remove();
                      alert(1);
                  }
              }

              orderCal();

              setDialogHeight();
          });
          $("#CategoryName").combobox({
              ColumnsMapsNodeName: 'ID|Name',
              TagObject: null,
              MustMatching: false,
              ListWidth: 250,
              DisplayHead: true,
              ListType: ListType.Combobox,
              DataType: DataType.Xml,
              DataLoadOnce: false,
              RemoteUrl: "/data/getxmldata?datatype=tourType&keyword=",
              TextFormat: 'V1',
              ValueFormat: 'V0,V1',
              OnItemClickEvent: function (src, data) {
                  var arrmp = data.value.split(",");
                  $("#CategoryID").attr("value", arrmp[0]);
                  $("#CategoryName").attr("value", arrmp[1]);
              },
              HeadColumn: [
            { name: "编号", width: 60 },
            { name: "名称" }
            ],
              KeyWordColumn: '',
              Buttons: [
            { text: "添加", event: function () { parent.showModalDialog('/Dict/Manage?dictKey=TOUR_CATE', false); } }
            ]
          });
      })

//end init

//重新排序日期的序号
function orderCal() {
    $(".calSNO").each(function (i) {
        $(this).text("第" + (i + 1) + "天");
    })

    $(".TC_TravelContent").each(function (i) {

        var id = $(this).attr("id");
        var initHtml = $(this).attr("initHtml");

        //alert(id);
        //        //没初始化得则初始化HTML编辑器
        if (id != "" && initHtml == undefined) {

            //alert(id);
            CKEDITOR.replace(id, ckConfig);

            $(this).attr("initHtml", true);
        }
    })
}

function addPriceRow() {
    var tr = $("#tbPrices tr").eq(1).clone();
    tr.appendTo("#tbPrices");
}


function editRow(src) {
    var objRow = $(src).parent().parent();
    objRow.removeClass("normal");
    objRow.addClass("edit");
}

function saveRow(src) {
    var objRow = $(src).parent().parent();
    var objInputs = $("input:text", objRow);
    var parm = objInputs.serialize() + "&DictKey=" + $("#DictKey").val();

    $.ajax({
        url: "/Dict/DoSaveDictInfo",
        type: "post",
        dataType: "json",
        data: parm,
        completed: function () { alert("complete") },
        success: saveRowCallback
    });
}

function saveRowCallback(result) {
    alert(result.ResultNo);
    alert(result.Message);

}

function delRow(dictID) {
    $("#act").val("del");
    $("#DictID").val(dictID);
    $("#frm").submit();
}

var ruleInex = -1;  //设置为-1不做任何操作
function selRule(index) {
    $(".rc").each(function (i) {
        if (index == i) {
            ruleInex = index;
            $(this).show();
        }
        else
            $(this).hide();
    })
}

//初始设置出团规则
function setRuleValue(val) {
    //alert(val);
    //alert($("input[name='ruleWeek']").length);

    if (val == "")
        selRule(0);
    else {
        var rules = val.split('|');
        selRule(rules[0]);

        switch (rules[0]) {
            case "0": //星期
                $("input[name='ruleWeek']").each(function (i) {
                    if (rules[1].indexOf(i) != -1)
                        $(this).attr("checked", "checked");
                })

                break;
            case "1": //指定日期
                var dates = rules[1].split(',')
                var strD = dates[0].replace(/-/g, "/");
                var d = new Date(strD);
                initCal(d.getFullYear(), d.getMonth() + 1, rules[1]);

                break;

            case "2": //间隔日期
                $("#ruleInterval").val(rules[1]);
                break;
        }

        if (rules[0] != 1) {
            var d = new Date();
            initCal(d.getFullYear(), d.getMonth() + 1, "");
        }
    }
}

//删除价格行
function delPriceRow(src) {
    $(src).parent().parent().remove();
}

//上下移动行日程 flag: 1 上移 2 下移
function moveRow(src, flag) {
    var curRow = $(src).parent().parent().parent().parent();

    if (flag == 1) {
        var preRow = curRow.prev();
        if (preRow.length == 0) return;
        curRow.insertBefore(preRow);

    } else {
        var nextRow = curRow.next();
        if (nextRow.length == 0) return;
        curRow.insertAfter(nextRow);
    }

    orderCal();
}

//选择用餐方式
function selectedDine(src, val) {
    var objDine = $(src).next();
    var objLi = $(src).parent();

    if (objDine.val() == "") {
        objDine.val(val); //选中
        objLi.addClass("selected");
    }
    else {
        objDine.val(""); //选中
        objLi.removeClass("selected");
    }
}

var currentCalendarID; //当前选择模板的ID

//设置当前操作行程的内容，供框架页调用
function setCalendarTemplate(content) {
    var js = "CKEDITOR.instances." + currentCalendarID + ".insertHtml('" + $.trim(content) + "')";
    //alert(js);
    eval(js);
    $("#dialog-message").dialog("close");
}
//打开设计行程页面
function selectedCalendarTemplate(src) {
    var row = $(src).parent().parent().parent().parent();
    var textarea = $(".TC_TravelContent", row);
    currentCalendarID = textarea.eq(0).attr("id");

    $("#dialog-message").dialog("open");
}


function addDate(type, NumDay, ddate) {
    var date = new Date(ddate);
    type = parseInt(type) //类型 
    lIntval = parseInt(NumDay)//间隔
    switch (type) {
        case 6: //年
            date.setYear(date.getYear() + lIntval)
            break;
        case 7: //季度
            date.setMonth(date.getMonth() + (lIntval * 3))
            break;
        case 5: //月
            date.setMonth(date.getMonth() + lIntval)
            break;
        case 4: //天
            date.setDate(date.getDate() + lIntval)
            break
        case 3: //时
            date.setHours(date.getHours() + lIntval)
            break
        case 2: //分
            date.setMinutes(date.getMinutes() + lIntval)
            break
        case 1: //秒
            date.setSeconds(date.getSeconds() + lIntval)
            break;
        default:

    }
    return date;
}


//日历跳转到指定月份, m 为 1 加一个月 -1 减一个月
function goCalMonth(m) {
    var d = new Date($("#ulCalendar").attr("date"));
    d = addDate(5, m, d);

    initCal(d.getFullYear(), d.getMonth() + 1, $("#ulCalendar").attr("value"));
}



//初始日历    defaultDate 默认日期，多个日期用,隔开
function initCal(year, month, defaultDate) {
    $("#ulCalendar li").remove();

    var now = new Date();
    var date1 = new Date(year, month, 1);
    var date2 = addDate(5, 1, date1);

    var day = parseInt(Math.abs(date2 - date1) / 1000 / 60 / 60 / 24);

    //设置日历日期
    $("#currentMonth").text(date1.getFullYear() + "-" + (date1.getMonth() + 1));

    var ulCalendar = document.getElementById("ulCalendar");
    ulCalendar.value = defaultDate; //默认日期
    ulCalendar.date = year + "/" + month + "/1"; //当前日历的日期

    for (var i = 1; i <= day; i++) {
        var li = document.createElement("li");
        var a = document.createElement("a");
        //a.innerText = "1";
        a.innerHTML = i;
        a.href = "javascript:void(0)";
        a.value = year + "-" + month + "-" + i;
        a.onclick = function () {
            var selectedValue = $("#ulCalendar").attr("value");
            var currentDate = $(this).attr("value");
            if ($(this).attr("class") == "selected") {
                $(this).attr("class", "");
                selectedValue = selectedValue.replace(currentDate, "");
            }
            else {
                $(this).attr("class", "selected");
                selectedValue += "," + currentDate;
            }
            $("#ulCalendar").attr("value", selectedValue);

            //alert(selectedValue);

            displaySelectedCalendar(); //显示选中的日期
        }

        //alert(defaultDate);
        //alert(a.value);
        if (defaultDate.indexOf(a.value) != -1)
            a.className = "selected";

        li.appendChild(a);
        ulCalendar.appendChild(li);
    }

    //alert(date2 > date1);
    displaySelectedCalendar(); //显示选中的日期
}

function displaySelectedCalendar() {
    $("#ulSelectedCalendar li").remove();
    var dates = $("#ulCalendar").attr("value").split(",");
    for (var i = 0; i < dates.length; i++) {
        if (dates[i] != "") {
            var li = document.createElement("li");
            li.innerHTML = dates[i];

            $("#ulSelectedCalendar").append(li);
        }
    }
}

